import { NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'

export async function PUT(
  request: Request,
  context: { params: { id: string } }
) {
  try {
    const [session, data, params] = await Promise.all([
      getServerSession(authOptions),
      request.json(),
      Promise.resolve(context.params)
    ])

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 })
    }

    const { id } = params

    // 检查场景是否存在且属于当前用户
    const existingScene = await prisma.scene.findFirst({
      where: { 
        id,
        userId: session.user.id
      }
    })

    if (!existingScene) {
      return NextResponse.json({ error: '场景不存在' }, { status: 404 })
    }

    // 更新场景
    const updatedScene = await prisma.scene.update({
      where: { id },
      data: {
        name: data.name,
        isActive: data.isActive,
        groupId: data.groupId,
        conditions: {
          deleteMany: {},
          create: data.conditions?.map((condition: any) => ({
            type: condition.type,
            operator: condition.operator,
            value: JSON.stringify(condition.value),
            sensorId: condition.sensorId
          })) || []
        },
        actions: {
          deleteMany: {},
          create: data.actions?.map((action: any) => ({
            type: action.type,
            deviceId: action.deviceId,
            value: JSON.stringify(action.value)
          })) || []
        },
        devices: {
          set: data.deviceIds?.map((id: string) => ({ id })) || []
        }
      },
      include: {
        conditions: true,
        actions: true,
        devices: true,
        group: true,
        tags: true,
        user: true
      }
    })

    return NextResponse.json(updatedScene)
  } catch (error: any) {
    console.error('更新场景失败:', error)
    return NextResponse.json(
      { error: error?.message || '更新场景失败' },
      { status: 500 }
    )
  }
}

export async function GET(
  request: Request,
  context: { params: { id: string } }
) {
  try {
    const params = await Promise.resolve(context.params)
    const { id } = params

    const scene = await prisma.scene.findUnique({
      where: { id },
      include: {
        conditions: true,
        actions: true,
        devices: true,
        group: true,
        tags: true,
        user: true
      }
    })

    if (!scene) {
      return NextResponse.json({ error: '场景不存在' }, { status: 404 })
    }

    return NextResponse.json(scene)
  } catch (error) {
    console.error('获取场景失败:', error)
    return NextResponse.json(
      { error: '获取场景失败' },
      { status: 500 }
    )
  }
}

export async function PATCH(
  request: Request,
  context: { params: { id: string } }
) {
  try {
    const [data, params] = await Promise.all([
      request.json(),
      Promise.resolve(context.params)
    ])
    const { id } = params

    const updatedScene = await prisma.scene.update({
      where: { id },
      data: {
        isActive: data.isActive
      },
      include: {
        conditions: true,
        actions: true,
        devices: true,
        tags: true,
        group: true
      }
    })

    return NextResponse.json(updatedScene)
  } catch (error) {
    console.error('更新场景状态失败:', error)
    return NextResponse.json(
      { error: '更新场景状态失败' },
      { status: 500 }
    )
  }
}

export async function DELETE(
  request: Request,
  context: { params: { id: string } }
) {
  try {
    const params = await Promise.resolve(context.params)
    const { id } = params

    await prisma.scene.delete({
      where: { id }
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('删除场景失败:', error)
    return NextResponse.json(
      { error: '删除场景失败' },
      { status: 500 }
    )
  }
} 